import {
    Button,
    Message,
    Switch,
    Table,
    TableInstance,
    Typography,
} from '@arco-design/web-react'
import React from 'react'
import MethodTag from '../../components/MethodTag'
import { apiStore } from '@/utils/store/apiStore'
import { IconDelete, IconEdit } from '@arco-design/web-react/icon'

export interface IApiItemsProps {
    // api列表
    apiItems: IApiItem[]
    // 删除api
    onDeleteApi?: (id: string) => void
    // 编辑api
    onEditApi?: (apiItem: IApiItem) => void
    // 需要更新
    onNeedUpdate?: () => void
}

const ApiItems: React.FC<IApiItemsProps> = ({
    apiItems,
    onDeleteApi,
    onEditApi,
    onNeedUpdate,
}) => {
    // 表格的高度
    const [tableScrollY, setTableScrollY] = useState('70vh')
    // 表格的dom
    const tableRef = useRef<TableInstance | null>(null)

    const getNameColumns = () => {
        // 至少有一个存在名称
        if (apiItems?.some((v) => !!v.label)) {
            return [
                {
                    title: '名称',
                    dataIndex: 'label',
                    width: 200,
                    ellipsis: true,
                },
            ]
        }
        return []
    }

    useEffect(() => {
        if (tableRef.current) {
            // 页面的高度
            const pageHeight = document.documentElement.clientHeight
            // 表格的top值
            const tableTop = tableRef.current
                .getRootDomElement()
                .getBoundingClientRect().top
            // 表格的高度
            const tableHeight = pageHeight - tableTop - 60
            setTableScrollY(Math.max(tableHeight, 500) + 'px')
        }
    }, [tableRef.current])

    return (
        <Table
            ref={tableRef}
            className='mt-2'
            pagination={false}
            rowKey='id'
            scroll={{ y: tableScrollY }}
            columns={[
                {
                    title: '序号',
                    dataIndex: 'id',
                    width: 80,
                    cellStyle: {
                        textAlign: 'center',
                    },
                    render: (_col, _item, index) => {
                        return index + 1
                    },
                },
                {
                    title: (
                        <>
                            <div className='flex items-center'>
                                启用
                                <Switch
                                    size='small'
                                    className='ml-1'
                                    checked={
                                        !!apiItems?.length &&
                                        !apiItems?.some((v) => !v.enabled)
                                    }
                                    onChange={async (v) => {
                                        const newApiItems = apiItems.map(
                                            (item) => {
                                                return {
                                                    ...item,
                                                    enabled: v,
                                                }
                                            },
                                        )
                                        await apiStore.save(newApiItems)
                                        onNeedUpdate?.()
                                        Message.success('操作成功')
                                    }}
                                />
                            </div>
                        </>
                    ),
                    dataIndex: 'enabled',
                    width: 100,
                    render: (col, item) => {
                        return (
                            <Switch
                                checked={col}
                                onChange={(v) => {
                                    apiStore
                                        .save({
                                            ...item,
                                            enabled: v,
                                        })
                                        .then(() => {
                                            Message.success('操作成功')
                                            onNeedUpdate?.()
                                        })
                                }}
                            />
                        )
                    },
                },
                ...getNameColumns(),
                {
                    title: '请求方法 & 地址',
                    dataIndex: 'url',
                    render: (col, item) => {
                        return (
                            <div>
                                <MethodTag method={item.method} />
                                <Typography.Text copyable>
                                    {col}
                                </Typography.Text>
                            </div>
                        )
                    },
                },
                {
                    title: '操作',
                    width: 220,
                    render: (_col, item) => {
                        return (
                            <div>
                                <Button
                                    type='text'
                                    icon={<IconEdit />}
                                    onClick={async () => {
                                        const apiItem =
                                            await apiStore.getListItem(item.id)
                                        if (
                                            !apiItem ||
                                            apiItem.type !== 'api'
                                        ) {
                                            Message.error('API不存在')
                                            return
                                        }
                                        onEditApi?.(apiItem)
                                    }}
                                >
                                    编辑
                                </Button>
                                <Button
                                    icon={<IconDelete />}
                                    type='text'
                                    className='ml-2'
                                    status='danger'
                                    onClick={() => {
                                        onDeleteApi?.(item.id)
                                    }}
                                >
                                    删除
                                </Button>
                            </div>
                        )
                    },
                },
            ]}
            data={apiItems}
        />
    )
}

export default ApiItems
